<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, initial-scale=1, shrink-to-fit=no">
    <div th:replace="~{admin/common :: common-link}"></div>
    <link th:href="@{'/admin/assets/js/plugins/dropzonejs/dist/min/dropzone.min.css'}" rel="stylesheet">
    <link rel="stylesheet" th:href="@{'/admin/assets/js/plugins/dropzonejs/dist/min/basic.min.css'}">
</head>
<body>

<div class="content">
    <div class="block block-fx-shadow">
        <div class="block-content">
            <div class="justify-content-center py-20">
                <div class="form-group row">
                    <label class="col-lg-4 col-md-2 col-form-label">主题文件 <span style="position: absolute; left: 75px;" title="主题文件必须是hexo-boot-theme系列"><i class="fa fa-info-circle"></i></span></label>
                    <div class="col-lg-8 col-md-8">
                        <form action="" method="post" enctype="multipart/form-data">
                            <input type="text" class="form-control" id="selectFile" readonly="readonly" style="height: 2.8rem; background: #fff; cursor: pointer" placeholder="请选择主题文件(.zip)">
                        </form>
                    </div>
                    <div class="col-lg-4 col-md-2">
                        <button type="button" class="btn btn-primary" id="uploadBtn">安装</button>
                    </div>
                </div>
                <div class="form-group row">
                    <div class="col-lg-12 col-md-12">
                        <textarea id="resultContainer" class="form-control" cols="30" rows="4" style="resize: none;overflow: auto;" disabled></textarea>
                    </div>
                </div>
                <div class="row" style="visibility: hidden" id="progressContainer">
                    <div class="col-lg-12 col-md-12">
                        <div class="progress push">
                            <div id="progressbar" class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" aria-valuenow="1" aria-valuemin="0" aria-valuemax="100">
                                <span id="progressText" class="progress-bar-label" style="max-width: unset">0%</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="form-group row">
                    <div class="col-lg-12 col-md-12">
                        <div>
                            <b>获取主题: </b><a href="https://extlight.com/repository/" target="_blank">资源仓库</a>&nbsp;&nbsp;
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div th:replace="~{admin/common :: common-script}"></div>
<script th:src="@{'/admin/assets/js/plugins/dropzonejs/dist/min/dropzone.min.js'}"></script>
<script type="text/javascript" th:inline="javascript">

    let themeManager = {
        init: function() {
            themeManager.initUploadEvent();
        },
        initUploadEvent: function() {
            Dropzone.autoDiscover = false;
            $("#selectFile").dropzone({
                method: "POST",
                url: "/admin/theme/unzipTheme.json", //上传地址
                addRemoveLinks: true,
                maxFiles: 2,// 一次性上传的文件数量上限
                maxFilesize: 30, // 单个上传文件大小，单位：MB
                previewsContainer: false,
                uploadMultiple: false, // 允许批量上传
                autoProcessQueue: false, // 是否自动上传
                acceptedFiles: ".zip",
                dictMaxFilesExceeded: "每次最多只能上传1个文件",
                dictResponseError: '文件上传失败',
                dictInvalidFileType: "支持上传主题源码 .zip 文件",
                dictFileTooBig: "最大支持20MB文件上传",
                init: function () {
                    let $progressbar = $("#progressbar");
                    let $progressText = $("#progressText");
                    let $resultContainer = $("#resultContainer");
                    let progress = 1;
                    let processInterval;
                    let myDropZone = this;
                    $("#uploadBtn").on("click", function(e) {
                        let that = this;
                        e.preventDefault();
                        let selectFileVal = $("#selectFile").val();
                        if (selectFileVal == "") {
                            $.hexo.modal.tip("请选择主题文件再上传", "info");
                            return;
                        }

                        $(that).prop("disabled", true);
                        document.getElementById("progressContainer").style.visibility = "visible";
                        $progressbar.width(progress + "%");
                        $progressText.text(progress + "%");
                        $resultContainer.val($resultContainer.val() + "\n正在上传【" + selectFileVal + "】主题压缩包......" + progress + "%");
                        processInterval = setInterval(function() {
                            progress += 1;
                            runProcess(progress, $progressbar, $progressText, $resultContainer, "正在上传【" + selectFileVal + "】主题压缩包");
                            if (progress >= 90) {
                                clearInterval(processInterval);
                            }
                        }, 50);

                        // 手动上传
                        myDropZone.processQueue();
                    });

                    this.on("addedfile", function (data) {

                        let acceptedFiles = this.getAcceptedFiles();
                        if (acceptedFiles.length > 0) {
                            this.removeFile(acceptedFiles[0]);
                        }

                        let selectFilename = data.name;
                        $("#selectFile").val(selectFilename);
                        $resultContainer.val("选择 " + selectFilename + " 主题文件");
                    });

                    this.on("error", function (data, message) {
                        if (typeof message == "string") {
                            $.hexo.modal.tip("上传失败: " + message, "error");
                        } else{
                            $.hexo.modal.tip("上传失败: " + message.error, "error");
                            window.parent.ThemeManager.query();
                            clearInterval(processInterval);
                            $resultContainer.val($resultContainer.val() + "\n" + message.error + "! 安装失败!");
                            $progressbar.removeClass("progress-bar-animated").addClass("bg-danger");
                        }
                    });

                    this.on("success", function (data, resp) {
                        clearInterval(processInterval);

                        let themeName = resp.data;

                        if (!resp.success) {
                            $.hexo.modal.tip("安装失败: " + resp.message, "error");
                            window.parent.ThemeManager.query();
                            clearInterval(processInterval);
                            $resultContainer.val($resultContainer.val() + "\n" + resp.message + "! 安装失败!");
                            $progressbar.removeClass("progress-bar-animated").addClass("bg-danger");
                            $resultContainer.scrollTop($resultContainer.prop("scrollHeight"));
                            return;
                        }

                        let num = 0;
                        let timer = setInterval(function() {
                            $.ajax({
                                type: "POST",
                                url: BASE_URL + "/checkThemeName.json",
                                data: {"themeName": themeName},
                                dataType: "JSON",
                                success: function (resp) {
                                    num++;
                                    console.log(resp);
                                    if (resp.data === true) {
                                        clearInterval(timer);

                                        processInterval = setInterval(function() {
                                            progress += 1;
                                            if (progress == 100) {
                                                clearInterval(processInterval);
                                                $progressbar.width("100%").removeClass("progress-bar-striped progress-bar-animated");
                                                $progressText.text("100%");
                                                $resultContainer.val($resultContainer.val() + "\n【" + themeName + "】主题安装成功......100%");
                                                $resultContainer.scrollTop($resultContainer.prop("scrollHeight"));
                                                $.hexo.modal.tip("操作成功", "success", function () {
                                                    window.parent.ThemeManager.query();
                                                });
                                                return;
                                            }
                                            runProcess(progress, $progressbar, $progressText, $resultContainer, "正在解压、安装【" + themeName + "】主题");
                                        }, 50);
                                    }

                                    // 10 秒内不能成功保存主题配置，视为失败
                                    if (num >= 10) {
                                        clearInterval(timer);
                                    }
                                }
                            });
                        }, 1000);
                    });
                }
            });
        }
    };

    function runProcess(progress, $progressbar, $progressText, $resultContainer, text) {
        $progressbar.width(progress + "%");
        $progressText.text(progress + "%");
        $resultContainer.val($resultContainer.val() + "\n" + text + "......" + progress + "%");
        $resultContainer.scrollTop($resultContainer.prop("scrollHeight"));
    }

    themeManager.init();

</script>
</body>
</html>